package com.easyboot.web.system.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.easyboot.utils.log.LoggerHelper;
import com.easyboot.constant.CookieConstants;
import com.easyboot.framework.domain.ResultAdaptDto;
import com.easyboot.enums.DataStatusEnum;
import com.easyboot.framework.properties.EasyBootConfig;
import com.easyboot.framework.shiro.UserOwnInfo;
import com.easyboot.framework.core.ActionResult;
import com.easyboot.framework.core.BaseController;
import com.easyboot.framework.core.RequestHelper;
import com.easyboot.web.system.domain.SysLoginLog;
import com.easyboot.web.system.domain.SysRole;
import com.easyboot.web.system.domain.SysUser;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;

import com.easyboot.web.system.service.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController extends BaseController {
    private  String DesKey = "#s^un2ye21fcv%|f0XpR,+vh";
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysLoginLogService loginLogService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private RequestHelper requestHelper;
    @Autowired
    private EasyBootConfig easyCmsConfig;
    @Autowired
    private Ip2regionSearcher regionSearcher;


    @GetMapping("/login")
    public ActionResult Index(Model model){

        model.addAttribute("projectName",easyCmsConfig.getName());
        model.addAttribute("copyrightYear", DateUtil.date().year());
        return view("/home/login");
    }


    @PostMapping("/loginOn")
    public ActionResult LoginOn(String username, String password, HttpServletResponse response){
        ResultAdaptDto result=new ResultAdaptDto();
        result.getData().put("username",username);
        result.getData().put("password", password);

        if(StrUtil.isEmpty(username)||StrUtil.isEmpty(password)){
            return error("用户名或者密码不能为空");
        }
        String ip= requestHelper.getIp();
        UserAgent ua = UserAgentUtil.parse(requestHelper.getHeader("User-Agent",""));

        String browser=StrUtil.format("{} {}",ua.getBrowser().toString(),ua.getVersion());
        SysUser user=userService.login(username.trim());
        SysLoginLog loginLog=new SysLoginLog();
        loginLog.setBrowser(browser);
        loginLog.setDeviceInfo(ua.getPlatform().toString());
        loginLog.setOsinfo(ua.getOs().toString());
        loginLog.setRequestIp(ip);
        loginLog.setLoginName(username);
        loginLog.setRequestTime(new Date());
        loginLog.setLoginStatus(1);
        loginLog.setLoginMessage("登录成功");
        if(NetUtil.isInnerIP(ip)){
            loginLog.setRealAddress("本地局域网");
        }else{

            String cityIpString=regionSearcher.getAddress(ip);
            loginLog.setRealAddress(cityIpString);
        }

        if(user==null){
            loginLog.setLoginMessage(StrUtil.format("用户:[{}]不存在",username));
            loginLog.setLoginStatus(0);
            loginLogService.addLoginLog(loginLog);
            return error(loginLog.getLoginMessage());
        }
        if(user.getUserStatus()==DataStatusEnum.DISABLE.getCode()){
            loginLog.setLoginMessage(StrUtil.format("用户:[{}]已禁用",username));
            loginLog.setLoginStatus(0);
            loginLogService.addLoginLog(loginLog);
            return error(loginLog.getLoginMessage());
        }
        if(!user.getPassWord().equals(password)){
            loginLog.setLoginMessage(StrUtil.format("用户:[{}]密码错误",username));
            loginLog.setLoginStatus(0);
            loginLogService.addLoginLog(loginLog);
            return error(loginLog.getLoginMessage());

        }

        loginLogService.addLoginLog(loginLog);

        //写入cookie
        UserOwnInfo userOwnInfo=new UserOwnInfo();
        BeanUtil.copyProperties(user, userOwnInfo);
        userOwnInfo.setDeptName(user.getDeptName());
        if(user.getRoleId()>0){
            SysRole role=roleService.getModel(user.getRoleId());
            if(role!=null){
                userOwnInfo.setRoleName(role.getRoleName());
                userOwnInfo.setRoleCode(role.getRoleCode());
            }
        }
        if(user.getIsSuper()==DataStatusEnum.SUPER.getCode()){
            userOwnInfo.setAdmin(true);
        }

        requestHelper.setUserCookie(userOwnInfo,response);

        result.put("url","/home/index");
        result.setMessage("登录成功");
        return json(result);
        //return ok("登录成功");
    }

    @GetMapping("/logout")
    public ActionResult  loginOut( HttpServletResponse response){

        Cookie userCookie = new Cookie(CookieConstants.LOGIN_COOKIE_NAME, null);
        userCookie.setMaxAge(0);
        response.addCookie(userCookie);
        return redirectTo("/login");
    }

    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }

}
